package com.railway.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.railway.bean.Carriage;
import com.railway.bean.Order;
import com.railway.bean.Orderdetailed;
import com.railway.bean.Seat;
import com.railway.bean.Ticket;
import com.railway.dao.OrderDao;
import com.railway.dao.TicketDao;
import com.railway.dao.TrainDao;
import com.railway.dao.impl.OrderDaoImpl;
import com.railway.dao.impl.TicketDaoImpl;
import com.railway.dao.impl.TrainDaoImpl;
import com.railway.service.OrderService;

public class OrderServiceImpl implements OrderService {

	OrderDao od = new OrderDaoImpl();
	TicketDao td = new TicketDaoImpl();
	
	@Override
	public int GenerateAnOrder(Map<String, String[]> map) {
		int order_id = CreateOrder(map);
		int train_id = Integer.parseInt(map.get("train_id")[0]);
		if(order_id != -1) {
			crateOrderDetailed(map, order_id,train_id);
		}
		return order_id;
	}

	@Override
	public int paidOrder(int order_id) {
		return od.updateOrderIsPaid(order_id);
	}

	public int CreateOrder(Map<String, String[]> map) {
		Order order = new Order();
		
		order.setUser_id(Integer.parseInt(map.get("user_id")[0]));
		
		order.setTrain_id(Integer.parseInt(map.get("train_id")[0]));
		
		DateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = dft.parse(map.get("starting_time")[0]);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		order.setTrain_date(date);
		
		order.setStatting_station_id(Integer.parseInt(map.get("statting_station_id")[0]));
		
		order.setTerminals_tation_id(Integer.parseInt(map.get("terminals_tation_id")[0]));
		
		Double order_price = 0.0;
		for (int i = 0; i <map.get("price")[0].length() ; i++) {
			order_price += Double.parseDouble((map.get("price[]")[i]));
		}
		order.setOrder_price(order_price);
		
		Date nowDate = new Date();
		order.setCreated_t(nowDate);
		
		order.setUse_integra(Integer.parseInt(map.get("use_integra")[0]));
		
		List<Order> o = od.selectOrdetId();
		
		int order_id =creteRandom(o);
		order.setOrder_id(order_id);
		int temp = od.insertOrder(order);
		if(temp > 0) {
			return order_id;
		}else {
			return -1;
		}
	}

	public void crateOrderDetailed(Map<String,String[]> map , int order_id,int train_id) {
		String seat_type[] = map.get("seat_type[]");
		int seat_num[] = new int[map.get("seat_num[]").length];
		char seat_location[] = new char[map.get("seat_num[]").length];
		int camrriage_num[] = new int[map.get("seat_num[]").length];
		Map<String,Map<String,Integer>> statisticsCamrriage = new HashMap<String, Map<String,Integer>>();
		boolean temp = true;
		boolean temp2 = true;
		
		for (int i = 0; i < seat_type.length; i++) {
			if(!seat_type[0].equals(seat_type[i])) {
				temp = false;
				break;
			}
		}
		
		for (int i = 0; i < seat_num.length; i++) {
			if(seat_num[0] != seat_num[i]) {
				temp2 = false;
				break;
			}
		}
		
		if(temp) {
			

			int seat_temp = -1;
			int camrriage_temp = -1;
			
			for (int i = 0; i < seat_type.length; i++) {
				Orderdetailed odt = new Orderdetailed();
				odt.setOder_detailed_id(od.selectOrdeTailedId(order_id)+1);
				odt.setOrder_id(order_id);
				odt.setPassenger_name(map.get("contact_name[]")[i]);
				odt.setPassenger_id_type(Integer.parseInt(map.get("contact_id_type[]")[i]));
				odt.setPassenger_id_num(map.get("contact_id_num[]")[i]);
				odt.setPassenger_type(Integer.parseInt(map.get("contact_passenger_type[]")[i]));
							
				odt.setSeat_type(Integer.parseInt(seat_type[i]));
				
				List<Ticket> tickets = td.selectTicket(train_id);
				
				List<Seat> Seat = selectLocation(train_id, Integer.parseInt(seat_type[i]), tickets);
				
				if(statisticsCamrriage.size() == 0) {
					
				
					
					Set<String> Keys2 = statisticsCamrriage.keySet();
					
					for (String key2 : Keys2) {
						Set<String> keys = statisticsCamrriage.get(key2).keySet();
						if(temp2) {
							for (String key : keys) {
								if(statisticsCamrriage.get(key2).get(key) == 5) {
									camrriage_temp = Integer.parseInt(key2);
									seat_temp = Integer.parseInt(key);
									break;
								}
							}
						}else {
							for (String key : keys) {
								if(statisticsCamrriage.get(key2).get(key) == 5 && statisticsCamrriage.get(key2).get(""+(Integer.parseInt(key)+1)) != null){
									if(statisticsCamrriage.get(key2).get(""+(Integer.parseInt(key)+1)) == 5) {
										camrriage_temp = Integer.parseInt(key2);
										seat_temp = Integer.parseInt(key);
										break;
									}
								}
							}
						}
					}
				}
				
				
				if(map.get("seat_num[]").length==1) {
					seat_num[0] = -1;
					for (Seat seat : Seat) {
						if(Character.toString(seat.getSeat_location()).equals(map.get("seat_location[]")[0] )) {
							camrriage_num[0] = seat.getCamage_num();
							seat_num[0] = seat.getSeat_num();
							seat_location[0] = seat.getSeat_location();
							break;
						}
					}
					if(seat_num[0] != -1) {
						odt.setCamage_num(camrriage_num[0]);
						odt.setSeat_num(seat_num[0]);
						odt.setSeat_location(seat_location[0]);
					}else{
						for (Seat seat : Seat) {
							odt.setCamage_num(seat.getCamage_num());
							odt.setSeat_num(seat.getSeat_num());
							odt.setSeat_location(seat.getSeat_location());
						}
					}
					od.insertOrderTailed(odt);
					//存数据库
				}else {
					if(temp2) {
						if(seat_temp != -1) {
							odt.setSeat_num(seat_temp);
							odt.setSeat_location(seat_location[i]);
						}else {
							for (Seat seat : Seat) {
								odt.setCamage_num(seat.getCamage_num());
								odt.setSeat_num(seat.getSeat_num());
								odt.setSeat_location(seat.getSeat_location());
							}
						}
					}else {
						if(camrriage_temp != -1 && seat_temp != -1) {
							if(seat_num[i]==1) {
								odt.setCamage_num(camrriage_temp);
								odt.setSeat_num(seat_temp);
								odt.setSeat_location(seat_location[i]);
							}else {
								odt.setCamage_num(camrriage_temp);
								odt.setSeat_num(seat_temp+1);
								odt.setSeat_location(seat_location[i]);
							}
						}else{
							for (Seat seat : Seat) {
								odt.setCamage_num(seat.getCamage_num());
								odt.setSeat_num(seat.getSeat_num());
								odt.setSeat_location(seat.getSeat_location());
							}
						}
					}
					od.insertOrderTailed(odt);
				}
			}
		}else{
			for (int i = 0; i < seat_type.length; i++) {
				Orderdetailed odt = new Orderdetailed();
				odt.setOder_detailed_id(od.selectOrdeTailedId(order_id)+1);
				odt.setOrder_id(order_id);
				odt.setPassenger_name(map.get("contact_name[]")[i]);
				odt.setPassenger_id_type(Integer.parseInt(map.get("contact_id_type[]")[i]));
				odt.setPassenger_id_num(map.get("contact_id_num[]")[i]);
				odt.setPassenger_type(Integer.parseInt(map.get("contact_passenger_type[]")[i]));
							
				odt.setSeat_type(Integer.parseInt(seat_type[i]));
				
				List<Ticket> tickets = td.selectTicket(train_id);
				
				List<Seat> Seat = selectLocation(train_id, Integer.parseInt(seat_type[i]), tickets);
			
				odt.setSeat_num(Seat.get(0).getSeat_num());
				odt.setSeat_location(seat_location[i]);
				
			}
		}
	}
	
	public List<Seat> selectLocation(int train_id,int seat_type,List<Ticket> tickets) {
		TrainDao trd = new TrainDaoImpl();
		List<Seat> seats = new ArrayList<Seat>();
		
		char locations[] = {'a','b','c','d','f'};
		List<Carriage> carriages = trd.selectCarriage(train_id);
		
		List<Order> orders = od.selectOrders(train_id);
		Date nowDate = new Date();
		
		//检索所有已被购买或被占的座位
		for (Order order : orders) {
			if((nowDate.getTime()-order.getCreated_at().getTime()) < (60*1000*20) || order.getIs_paid() == 1) {
				List<Orderdetailed> orderdetaileds = od.selectOrdeTailed(order.getOrder_id());
				for (Orderdetailed orderdetailed : orderdetaileds) {
					Seat seat = new Seat(orderdetailed.getCamage_num(),orderdetailed.getSeat_num(),orderdetailed.getSeat_location());
					seats.add(seat);
				}
			}
		}
		return selecTvacancy(carriages, seats, seat_type);
	}
	
	public List<Seat> selecTvacancy(List<Carriage> carriages,List<Seat> seats,int seat_type){
		
		char locations[] = {'a','b','c','d','f'};
		List<Seat> vacancySeat = new ArrayList<Seat>();
		
		//检索所有此类型的空位
		for (Carriage carriage : carriages) {
			if(carriage.getCarriage_type() == seat_type) {
				for (int i = 0; i < carriage.getSeat_num(); i++) {
					for (int j = 0; j < 5; j++) {
						boolean temp = true;
						for (Seat seat : seats) {
							if(carriage.getCarriage_num() == seat.getCamage_num()) {
								if(seat.getSeat_num() == i && seat.getSeat_location() == locations[j] ) {
									 temp = false;
									 break;
								}
							}
						}
						if(temp) {
							Seat s = new Seat(carriage.getCarriage_num(),i,locations[j]);
							vacancySeat.add(s);
						}
					}
				}
			}
		}
		return vacancySeat;
	}
	
	public int creteRandom(List<Order> o) {
		int i = (int)(Math.random()*1000000000);
		for (Order temp : o) {
			if(temp.getOrder_id() == i) {
				creteRandom(o);
			}
		}
		return i;
	}

	@Override
	public List<Order> selectOrderByUserId(int user_id) {
		List<Order> orders = od.slectOrderByUserId(user_id);
		for (Order order : orders) {
			order.setOrderdetaileds(od.selectOrdeTailed(order.getOrder_id()));
		}
		return orders;
	}

	@Override
	public List<Order> selectOrderUnpaidByUserId(int user_id) {
		List<Order> orders =  od.selectOrderUnpaidByUserId(user_id);
		for (Order order : orders) {
			order.setOrderdetaileds(od.selectOrdeTailed(order.getOrder_id()));
		}
		return orders;
	}

	@Override
	public List<Order> selectOrderUntravelByUserId(int user_id) {
		return od.selectOrderUntravelByUserId(user_id);
	}

	@Override
	public List<Order> selectOrderAllByUserId(int user_id) {
		return od.selectOrderAllByUserId(user_id);
	}

	@Override
	public List<Order> selectOrderticketchangingByUserId(int user_id) {
		return od.selectOrderticketchangingByUserId(user_id);
	}

	@Override
	public List<Order> selectOrderRefundByUserId(int user_id) {
		// TODO Auto-generated method stub
		return od.selectOrderRefundByUserId(user_id);
	}
}
